const app = getApp();
Page({
  data: {
    xhx_images: app.xhx_images,
    xhx_route: app.xhx_route,
    countDown:60,
    isClickGetCode:false,//是否点击过获取验证码
  },
  changePhone,//手机号
  getCode,//获取验证码
  sendPhoneCode,//获取验证码请求
  bindPhoneWithUser,//手机号绑定
})

function changePhone(event){
  const that = this;
  const phone = event.detail.value;
  that.setData({
    phone,
  })
}

function getCode(){
  const that = this;
  let phone = that.data.phone;
  phone=phone.replace(/[^0-9]/ig,"");
  if (app.middleware.isPoneAvailable(phone)){

    that.sendPhoneCode();
    that.setData({
      phone,
      isClickGetCode:true,
      countDown: that.data.countDown - 1,
    })
    var timmer = setInterval(()=>{
      that.setData({
        countDown: that.data.countDown-1,
      })
      if(that.data.countDown == 0){
         clearInterval(timmer);
         that.setData({
           countDown:60,
         })
        return false;
      }
    },1000)
  }else{
    app.middleware.showToast("手机号错误");
  }
}

function sendPhoneCode(){
  const that = this;
  const phone = that.data.phone;
  var reqData={
    phone: phone  //手机号
  }
  app.middleware.requestAjax({
    serAddr: app.serAddrs.sendPhoneCode,
    data: reqData,
    cancelToast: true,
    success: function (res) {
      
    }
  })
}

function bindPhoneWithUser(event){
  const that =this;
  const isClickGetCode = that.data.isClickGetCode;
  const phone = event.detail.value.phone;
  const code = event.detail.value.code;

  if (!isClickGetCode) return app.middleware.showToast("请获取验证码");
  else if (!app.middleware.isPoneAvailable(phone)) return app.middleware.showToast("手机号错误");
  else if (!code) return app.middleware.showToast("请输入验证码");

  var reqData = {
    phone: phone,  //手机号
    code: code,    //验证码
  }

  app.middleware.requestAjax({
    serAddr: app.serAddrs.bindPhoneWithUser,
    data: reqData,
    cancelToast: true,
    success: function (res) {
      app.userInfo = Object.assign({}, app.userInfo || {}, res.data || {});
      setTimeout(()=>wx.navigateBack(),2000);
    },
    complete:function(res){
      app.middleware.showToast(res && res.msg || "操作失败");
    }
  })
}